package bma.common.netty;

import java.nio.charset.Charset;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.util.CharsetUtil;

import bma.common.netty.client.NettyClient;

public class NettyUtil {

	public static final String HANDLER_PLACEHOLDER = "handlerPlaceholder";

	public static void closeOnFlush(Channel ch) {
		if (ch.isConnected()) {
			ch.write(ChannelBuffers.EMPTY_BUFFER).addListener(
					ChannelFutureListener.CLOSE);
		}
	}

	public static void closeOnFlush(NettyClient nc) {
		if (nc.isConnected()) {
			nc.write(ChannelBuffers.EMPTY_BUFFER).addListener(
					nc.closeListener());
		}
	}

	public static Charset getContentType(HttpResponse response) {
		String contentType = response.getHeader(HttpHeaders.Names.CONTENT_TYPE);
		if (contentType != null) {
			for (String part : contentType.split(";")) {
				if (part.trim().startsWith("charset=")) {
					String[] val = part.split("=");
					if (val[1] != null) {
						return Charset.forName(val[1].trim());
					}
				}
			}
			return null;
		}
		return CharsetUtil.UTF_8;
	}
}
